/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jhu.profiteer;

import java.io.IOException;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import jhu.profiteer.data.Account;
import jhu.profiteer.data.AccountJpaController;
import java.util.regex.Matcher;  
import java.util.regex.Pattern;  

/**
 *
 * @author Jeremy, Shiva
 */
public class CreateAccount extends HttpServlet 
{
   
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException 
    {
      String submit = request.getParameter("submit");
      String url = "";

      // check for submit
      if(null == submit)
      {
        this.getServletContext()
                .getRequestDispatcher("/index")
                .forward(request, response);
        return;
      }

      HttpSession session = request.getSession();
      Vector<String> notices = (Vector<String>)session.getAttribute("notices");
      AccountJpaController jc = new AccountJpaController();

      // submit = cancel
      if(submit.equalsIgnoreCase("Cancel")) url = "/index";
      // submit = login
      else if(submit.equalsIgnoreCase("Create Account"))
      {
        url = "/newAccount";
        boolean save = true;
        boolean passCompare = true;

        // check account name
        String name = request.getParameter("accountName");

        if((null == name) || name.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply an account name.");
          save = false;
        }

        // check account name in database
        if(null != name && !name.isEmpty())
        {
          if (true == jc.testForAccountWithName(name)) // account found
          {
            if(null == notices) notices = new Vector<String>();
            notices.add("Account Name already exists, Please pick another user name.");
            save = false;
          }
        }

        // check password
        String pass = request.getParameter("password");

        if((null == pass) || pass.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply a password.");
          save = false;
          passCompare = false;
        }

        // check confirm password
        String confirm = request.getParameter("confirm");

        if((null == confirm) || confirm.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply a confirm password.");
          save = false;
          passCompare = false;
        }

        // check password and confirm password matches
        if(passCompare)
        {
          if(!pass.equals(confirm))
          {
            if(null == notices) notices = new Vector<String>();
            notices.add("Password & Confirm password not matching.");
            save = false;
          }
        }

        // check email
        String email = request.getParameter("email");

        if((null == email) || email.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply a email address.");
          save = false;
        }

        // validate email address
        if(null != email && !email.isEmpty())
        {
          String  expression = "^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
          Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);
          Matcher matcher = pattern.matcher(email);

          if (!matcher.matches())
          {
            if(null == notices) notices = new Vector<String>();
            notices.add("Email address is not a valid one.");
            save = false;
          }
        }

        // no check fails, so create
        if(save)
        {
          Account a = new Account();
          a.setName(name);
          a.setAdministrator(false);
          a.setDamaged(false);
          a.setPassword(pass);
          a.setEmailAddress(email);
          jc.create(a);
          url = "/characterInformation";
          session.setAttribute("account", a);
        }
      }

      if(null != notices) session.setAttribute("notices", notices);
      // forward request
      this.getServletContext()
              .getRequestDispatcher(url)
              .forward(request, response);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
